package com.kzw.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;

import my.json.Jackson;
import my.util.ResponseUtils;
import my.vo.Record;

@MultipartConfig
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 通过AJAX方式
	 * */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("UTF-8");
		
		// 根据名称获得附件：layui默认是file
		Part part = req.getPart("file");
		if(part != null) {
			String fname = part.getSubmittedFileName(); //文件原名称
			InputStream is = part.getInputStream();
			
			String upload = req.getServletContext().getRealPath("/upload");
			OutputStream os = new FileOutputStream(new File(upload, fname));
			
			IOUtils.copy(is, os);
			is.close();
			os.close();
			
			// layui上传完成，获得JSON
			Map<String, Object> data = new HashMap<>();
			data.put("src", "/upload/" + fname);
			Record ret = new Record(true, 0, "上传完成");
			ret.setData(data);
			
			String json = Jackson.me().toJson(ret);
			ResponseUtils.renderJson(resp, json);
		}
		
		
	}
	
}
